<template>
  <div class="questions">
    <div class="page-header">
      <h1>题库管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true" v-if="currentExamId">
          <el-icon><Plus /></el-icon>
          添加题目
        </el-button>
        <el-button @click="showExamSelector = true">
          <el-icon><Document /></el-icon>
          选择考试
        </el-button>
      </div>
    </div>

    <!-- 当前考试信息 -->
    <div v-if="currentExam" class="current-exam">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>当前考试：{{ currentExam.title }}</span>
            <el-tag :type="getStatusType(currentExam.status)">
              {{ getStatusText(currentExam.status) }}
            </el-tag>
          </div>
        </template>
        <div class="exam-info">
          <div class="info-item">
            <span class="label">题目数量：</span>
            <span class="value">{{ currentExam.question_count || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="label">考试时长：</span>
            <span class="value">{{ currentExam.duration }} 分钟</span>
          </div>
          <div class="info-item">
            <span class="label">总分：</span>
            <span class="value">{{ currentExam.total_score }}</span>
          </div>
          <div class="info-item">
            <span class="label">及格分：</span>
            <span class="value">{{ currentExam.pass_score }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选器 -->
    <div class="filters" v-if="currentExamId">
      <el-select v-model="typeFilter" placeholder="题型筛选" style="width: 150px; margin-right: 10px;" @change="loadQuestions">
        <el-option label="全部" value="" />
        <el-option label="单选题" value="single_choice" />
        <el-option label="多选题" value="multiple_choice" />
        <el-option label="判断题" value="true_false" />
        <el-option label="填空题" value="fill_blank" />
        <el-option label="简答题" value="essay" />
      </el-select>
      <el-input
        v-model="searchQuery"
        placeholder="搜索题目内容"
        style="width: 300px;"
        @input="handleSearch"
      />
    </div>

    <!-- 题目列表 -->
    <el-table 
      :data="questions" 
      style="width: 100%" 
      v-loading="loading"
      v-if="currentExamId"
    >
      <el-table-column prop="content" label="题目内容" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="question-content">
            <div class="question-text">{{ row.content }}</div>
            <el-tag size="small" :type="getQuestionTypeType(row.question_type)">
              {{ getQuestionTypeText(row.question_type) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="options" label="选项" width="300">
        <template #default="{ row }">
          <div class="question-options" v-if="row.options">
            <div 
              v-for="(option, index) in parseOptions(row.options)" 
              :key="index"
              class="option-item"
            >
              <span class="option-key">{{ option.key }}.</span>
              <span class="option-value">{{ option.value }}</span>
              <el-tag 
                v-if="isCorrectOption(row.correct_answer, option.key)"
                size="small" 
                type="success"
              >
                正确答案
              </el-tag>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="score" label="分值" width="80" />
      <el-table-column prop="order_num" label="排序" width="80" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无考试选择提示 -->
    <div v-else class="no-exam">
      <el-empty description="请先选择一个考试来管理题目">
        <el-button type="primary" @click="showExamSelector = true">
          选择考试
        </el-button>
      </el-empty>
    </div>

    <!-- 考试选择对话框 -->
    <el-dialog
      v-model="showExamSelector"
      title="选择考试"
      width="600px"
    >
      <el-table :data="availableExams" style="width: 100%" v-loading="examsLoading">
        <el-table-column prop="title" label="考试名称" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="question_count" label="题目数量" width="100" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="selectExam(row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 创建题目对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="添加题目"
      width="700px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="questionFormRef"
        :model="questionForm"
        :rules="questionRules"
        label-width="100px"
      >
        <el-form-item label="题目类型" prop="question_type">
          <el-select v-model="questionForm.question_type" placeholder="请选择题目类型" @change="handleQuestionTypeChange">
            <el-option label="单选题" value="single_choice" />
            <el-option label="多选题" value="multiple_choice" />
            <el-option label="判断题" value="true_false" />
            <el-option label="填空题" value="fill_blank" />
            <el-option label="简答题" value="essay" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="题目内容" prop="content">
          <el-input
            v-model="questionForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入题目内容"
          />
        </el-form-item>
        
        <el-form-item label="选项" prop="options" v-if="showOptions">
          <div class="options-container">
            <div 
              v-for="(option, index) in optionList" 
              :key="index"
              class="option-input"
            >
              <el-input
                v-model="option.value"
                :placeholder="`选项 ${option.key}`"
                style="margin-bottom: 10px;"
              >
                <template #prefix>
                  <span class="option-key">{{ option.key }}.</span>
                </template>
              </el-input>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="正确答案" prop="correct_answer">
          <el-select
            v-model="questionForm.correct_answer"
            :placeholder="getCorrectAnswerPlaceholder()"
            :multiple="questionForm.question_type === 'multiple_choice'"
          >
            <el-option 
              v-for="option in optionList" 
              :key="option.key"
              :label="`${option.key}. ${option.value}`"
              :value="option.key"
              v-if="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="分值" prop="score">
          <el-input-number
            v-model="questionForm.score"
            :min="1"
            :max="100"
            placeholder="请输入分值"
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="order_num">
          <el-input-number
            v-model="questionForm.order_num"
            :min="1"
            :max="1000"
            placeholder="请输入排序"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreate" :loading="creating">
            添加
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import api from '../api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Document } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

const questions = ref([]);
const availableExams = ref([]);
const currentExam = ref(null);
const loading = ref(false);
const creating = ref(false);
const examsLoading = ref(false);
const showCreateDialog = ref(false);
const showExamSelector = ref(false);
const questionFormRef = ref();

// 筛选条件
const searchQuery = ref('');
const typeFilter = ref('');
const currentExamId = ref(route.query.exam_id || '');

// 题目表单
const questionForm = reactive({
  content: '',
  question_type: 'single_choice',
  options: '',
  correct_answer: '',
  score: 5,
  order_num: 1
});

// 选项列表
const optionList = ref([
  { key: 'A', value: '' },
  { key: 'B', value: '' },
  { key: 'C', value: '' },
  { key: 'D', value: '' }
]);

// 表单验证规则
const questionRules = {
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 5, max: 1000, message: '题目内容长度在 5 到 1000 个字符', trigger: 'blur' }
  ],
  question_type: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  correct_answer: [
    { required: true, message: '请选择正确答案', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' }
  ],
  order_num: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
};

// 计算属性
const showOptions = computed(() => {
  return ['single_choice', 'multiple_choice'].includes(questionForm.question_type);
});

const getStatusType = (status) => {
  const statusMap = {
    'draft': 'info',
    'published': 'success',
    'ongoing': 'warning',
    'completed': 'danger'
  };
  return statusMap[status] || 'info';
};

const getStatusText = (status) => {
  const statusMap = {
    'draft': '草稿',
    'published': '已发布',
    'ongoing': '进行中',
    'completed': '已完成'
  };
  return statusMap[status] || '未知';
};

const getQuestionTypeType = (type) => {
  const typeMap = {
    'single_choice': 'primary',
    'multiple_choice': 'warning',
    'true_false': 'success',
    'fill_blank': 'info',
    'essay': 'danger'
  };
  return typeMap[type] || 'info';
};

const getQuestionTypeText = (type) => {
  const typeMap = {
    'single_choice': '单选题',
    'multiple_choice': '多选题',
    'true_false': '判断题',
    'fill_blank': '填空题',
    'essay': '简答题'
  };
  return typeMap[type] || '未知';
};

const parseOptions = (options) => {
  try {
    const parsed = JSON.parse(options);
    return Object.entries(parsed).map(([key, value]) => ({ key, value }));
  } catch (e) {
    return [];
  }
};

const isCorrectOption = (correctAnswer, optionKey) => {
  if (Array.isArray(correctAnswer)) {
    return correctAnswer.includes(optionKey);
  }
  return correctAnswer === optionKey;
};

const getCorrectAnswerPlaceholder = () => {
  const typeMap = {
    'single_choice': '请选择正确答案',
    'multiple_choice': '请选择正确答案（可多选）',
    'true_false': '请选择正确答案',
    'fill_blank': '请输入正确答案',
    'essay': '请输入参考答案'
  };
  return typeMap[questionForm.question_type] || '请输入正确答案';
};

const loadQuestions = async () => {
  if (!currentExamId.value) return;
  
  loading.value = true;
  try {
    const params = {
      exam_id: currentExamId.value,
      question_type: typeFilter.value || undefined
    };
    
    const response = await api.questions.getQuestions(params);
    questions.value = response.data;
  } catch (error) {
    ElMessage.error('加载题目列表失败');
  } finally {
    loading.value = false;
  }
};

const loadAvailableExams = async () => {
  examsLoading.value = true;
  try {
    const response = await api.exams.getExams({ limit: 100 });
    availableExams.value = response.data.items;
  } catch (error) {
    ElMessage.error('加载考试列表失败');
  } finally {
    examsLoading.value = false;
  }
};

const loadCurrentExam = async () => {
  if (!currentExamId.value) return;
  
  try {
    const response = await api.exams.getExamDetail(currentExamId.value);
    currentExam.value = response.data;
  } catch (error) {
    ElMessage.error('加载考试信息失败');
  }
};

const handleSearch = () => {
  loadQuestions();
};

const selectExam = (exam) => {
  currentExamId.value = exam.id;
  currentExam.value = exam;
  showExamSelector.value = false;
  router.push({ query: { exam_id: exam.id } });
  loadQuestions();
};

const handleQuestionTypeChange = (type) => {
  // 重置表单相关字段
  questionForm.correct_answer = '';
  
  // 根据题目类型调整选项
  if (type === 'true_false') {
    optionList.value = [
      { key: 'A', value: '正确' },
      { key: 'B', value: '错误' }
    ];
  } else if (type === 'single_choice' || type === 'multiple_choice') {
    optionList.value = [
      { key: 'A', value: '' },
      { key: 'B', value: '' },
      { key: 'C', value: '' },
      { key: 'D', value: '' }
    ];
  } else {
    optionList.value = [];
  }
};

const handleCreate = async () => {
  if (!questionFormRef.value) return;
  
  await questionFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      creating.value = true;
      try {
        // 构建选项对象
        let options = {};
        if (showOptions.value) {
          optionList.value.forEach(option => {
            if (option.value) {
              options[option.key] = option.value;
            }
          });
        }
        
        const questionData = {
          ...questionForm,
          exam_id: currentExamId.value,
          options: Object.keys(options).length > 0 ? JSON.stringify(options) : null
        };
        
        await api.questions.createQuestion(questionData);
        ElMessage.success('题目添加成功');
        showCreateDialog.value = false;
        resetForm();
        loadQuestions();
        
        // 更新考试题目数量
        loadCurrentExam();
      } catch (error) {
        ElMessage.error('添加题目失败');
      } finally {
        creating.value = false;
      }
    }
  });
};

const handleEdit = (question) => {
  ElMessage.info('编辑功能开发中...');
};

const handleDelete = async (question) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这道题目吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await api.questions.deleteQuestion(question.id);
    ElMessage.success('题目删除成功');
    loadQuestions();
    
    // 更新考试题目数量
    loadCurrentExam();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除题目失败');
    }
  }
};

const handleDialogClose = () => {
  showCreateDialog.value = false;
  resetForm();
};

const resetForm = () => {
  if (questionFormRef.value) {
    questionFormRef.value.resetFields();
  }
  Object.assign(questionForm, {
    content: '',
    question_type: 'single_choice',
    options: '',
    correct_answer: '',
    score: 5,
    order_num: 1
  });
  
  optionList.value = [
    { key: 'A', value: '' },
    { key: 'B', value: '' },
    { key: 'C', value: '' },
    { key: 'D', value: '' }
  ];
};

// 监听路由参数变化
watch(() => route.query.exam_id, (newExamId) => {
  currentExamId.value = newExamId || '';
  if (newExamId) {
    loadCurrentExam();
    loadQuestions();
  } else {
    currentExam.value = null;
    questions.value = [];
  }
});

onMounted(() => {
  loadAvailableExams();
  if (currentExamId.value) {
    loadCurrentExam();
    loadQuestions();
  }
});
</script>

<style scoped>
.questions {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.current-exam {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-info {
  display: flex;
  gap: 30px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  color: #909399;
  margin-right: 8px;
}

.info-item .value {
  font-weight: bold;
  color: #303133;
}

.filters {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.question-content {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.question-text {
  flex: 1;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.option-key {
  font-weight: bold;
  color: #409EFF;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-input {
  display: flex;
  align-items: center;
}

.option-key {
  font-weight: bold;
  color: #409EFF;
  margin-right: 5px;
}

.no-exam {
  text-align: center;
  padding: 40px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>